package com.ss.whisper2.controller;

import com.ss.whisper2.pojo.Result;
import com.ss.whisper2.pojo.State;
import com.ss.whisper2.pojo.entity.user.User;
import com.ss.whisper2.pojo.vo.LoginVO;
import com.ss.whisper2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller

public class LoginController {
	@Autowired
	UserService userService;
	@GetMapping({"","/","/index"})
	public String home() {
		return "index";
	}

	@GetMapping("login")
	public String login() {
		return "login";
	}

	@PostMapping("login")
	@ResponseBody
	public Result<String> login(@RequestBody LoginVO loginVO,HttpSession session) {
		User dbUser = userService.validate(loginVO.getUsername(), loginVO.getPassword());
		//登录信息保存到数据库
		//userService.recordLoginUser(username);
		//密码置空
		dbUser.setPassword(null);
		//session保存用户信息
		session.setAttribute("user",dbUser);
		//设置有效期为30分钟
		session.setMaxInactiveInterval(30 * 60);
		//取出被拦截器拦截之前想要访问的地址
		String target=(String)session.getAttribute("target");
		if (target!= null&&!target.equals("login")) {
			session.setAttribute("target",null);
			return new Result<>(State.SUCCESS,target);
		}else {
			return new Result<>(State.SUCCESS,"/");
		}

	}
	@GetMapping("/logout")
	public String logOut(HttpSession session,Model model) {
		session.removeAttribute("user");
		session.setMaxInactiveInterval(0);
		session.invalidate();
		model.addAttribute("msg", "注销成功");
		return "redirect:";
	}

}
